// scale.js
Page({
  data: {
    array: ['盐', '碘盐', '糖', '油'],
    userInfor: [],
    index: 0,
    show: false, // 日期卡展示
    tiaoliaoShow: false, //调料展示
    dateNow: '', // 当前日期
    condiment: '碘盐', // 调味品种类
    IinSalt: 25, // 含碘量（mg/kg）
    weight: 0.0, // 当前称重示数（g）
    remark: '午餐', // 备注
    mqtt: { // MQTT协议相关数据
      uid: '04f2328bfe7e467d92c156adef0da514', // 用户秘钥
      topic: { // 各种功能使用的主题
        send: 'WeChattoESP', // 发送数据时使用的主题
        get: 'ESPtoWeChat', // 接收数据时使用的主题
        check: 'OTA' // 检查在线状态时使用的主题
      },
      url: { // 用到的TCP接口
        checkOnline: 'https://api.bemfa.com/mqtt/status/', // 检查设备是否在线
        getMessage: 'https://api.bemfa.com/api/device/v1/data/3/get/', // 获取主题中的信息
      }
    },
    device: { // 设备状态
      name: '未连接称重设备', // 设备名
      status: '离线' // 网络状态
    },
    record: { // 需要存储到本地的数据
      salt: 3, // 盐总摄入量（g）
      iodine: 7, // 碘总摄入量（mg）
      sugar:5, // 糖总摄入量（g）
      oil: 8 // 油总摄入量（g）
    }
  },
  onTiaoliaoDisplay: function(){
    this.setData({ tiaoliaoShow: true });
  },
  onTiaoliaoClose: function() {
    this.setData({ tiaoliaoShow: false });
  },
  onTiaoliaoCancel: function() {
    this.setData({ tiaoliaoShow: false });
  },
  onTiaoliaoConfirm: function(event) {
    this.setData({
      tiaoliaoShow: false,
      condiment: event.detail.value,
    });
  },
  onDisplay: function() {
    this.setData({ show: true });
  },
  onClose: function() {
    this.setData({ show: false });
  },
  formatDate: function(date) {
    date = new Date(date);
    return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
  },
  onConfirm: function(event) {
    this.setData({
      show: false,
      dateNow: this.formatDate(event.detail),
    });
  },
  // 日期修改响应
  bindDateChange: function(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      dateNow: e.detail.value
    })
  },
 // 修改调料选择
  bindPickerChange: function(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      index: e.detail.value
    })
    console.log('修改userInfo')
    this.data.userInfor.push({userName: 'aaa', pwd:'111111'})
    this.setData({
      userInfor: this.data.userInfor
    })
    console.log(this.data.userInfor)
  },
  onLoad: function (options) {
    console.log('[user] [scale] onLoad');
    // 设置定时任务
    setInterval(this.getWeight_Interval, 500);
  },
  onShow: function () {
    console.log('[user] [scale] onShow');
    // 读取本地数据
    this.setData({
      record: wx.getStorageSync('dataRecord')
    });
    console.log('[user] [scale] Got record: ' + JSON.stringify(this.data.record));
    // 获取当前日期
    let date = new Date();
    this.setData({
      dateNow: date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate()
    });
  },
  onHide: function () {
    console.log('[user] [scale] onHide');
    wx.setStorage({
      key: 'dataRecord',
      data: this.data.record,
      success () {
        wx.getStorage({
          key: 'dataRecord',
          success(res){
            console.log('[user] [scale] Data stored:' + JSON.stringify(res.data));
          }
        });
      },
      fail (res) {
        console.log('[user] [scale] [Error] reuqest failed! Code:' + res);
      }
    });
  },
  /** 检查设备在线状态
   *
   * 调用mqtt云的TCP接口，检查主题是否有设备订阅以判断设备在线状态，若在线则返回true
   */
  checkOnline: function () {
    let that = this;
    wx.request({
      url: that.data.mqtt.url.checkOnline,
      data: {
        uid: that.data.mqtt.uid,
        topic: that.data.mqtt.topic.check,
      },
      success(res){
        if(res.data.status == 'online') {
          that.setData({
            device: {
              name: 'ESP8266',
              status: '在线'
            }
          });
        } else if(res.data.status == 'offline') {
          that.setData({
            device: {
              name: '未连接称重设备',
              status: '离线'
            }
          });
        }
        console.log('[user] [scale] [checkOnline] [Error] ' + JSON.stringify(res.data));
      },
      fail (res) {
        console.log('[user] [scale] [checkOnline] [Error] reuqest failed! Code:' + res);
      }
    });
  },
  /** 获取电子秤当前读数
   *
   * 周期执行，通过接收mqtt相应主题的消息获取电子秤当前读数，并将其更新到data.device.weight中
   */
  getWeight_Interval: function () {
    let that = this;
    this.checkOnline();
    if(this.data.device.status == '在线') {
      wx.request({
        url: that.data.mqtt.url.getMessage,
        data: {
          uid: that.data.mqtt.uid,
          topic: that.data.mqtt.topic.get
        },
        success(res){
          that.setData({
            weight: res.data.data[0].msg
          })
          console.log(res)
        },
        fail (res) {
          console.log('[user] [scale] [getWeight_Interval] [Error] reuqest failed! Code:' + res);
        }
      });
    }
  },
  /** 
   * 
   */
  recordData: function () {
    if(this.data.device.status == '在线') {
      switch (this.data.condiment) {
        case '碘盐':
          this.setData({
            record: {
              salt: this.data.record.salt + this.data.weight,
              iodine: this.data.record.iodine + (this.data.weight / 1000.0 * this.data.IinSalt),
              sugar: this.data.record.sugar,
              oil: this.data.record.oil,
            }
          });
          console.log('[user] [scale] ADI: {iodinizedsalt: ' + this.data.weight + ' g}');
          console.log('[user] [scale] Data recorded: ' + JSON.stringify(this.data.record));
          break;
        case '盐':
          this.setData({
            record: {
              salt: this.data.record.salt + this.data.weight,
              iodine: this.data.record.iodine,
              sugar: this.data.record.sugar,
              oil: this.data.record.oil,
            }
          });
          console.log('[user] [scale] ADI: {salt: ' + this.data.weight + ' g}');
          console.log('[user] [scale] Data recorded: ' + JSON.stringify(this.data.record));
          break;
        case '糖':
          this.setData({
            record: {
              salt: this.data.record.salt,
              iodine: this.data.record.iodine,
              sugar: this.data.record.sugar + this.data.weight,
              oil: this.data.record.oil,
            }
          });
          console.log('[user] [scale] ADI: {sugar: ' + this.data.weight + ' g}');
          console.log('[user] [scale] Data recorded: ' + JSON.stringify(this.data.record));
          break;
        case '油':
          this.setData({
            record: {
              salt: this.data.record.salt,
              iodine: this.data.record.iodine,
              sugar: this.data.record.sugar,
              oil: this.data.record.oil + this.data.weight,
            }
          });
          console.log('[user] [scale] ADI: {oil: ' + this.data.weight + ' g}');
          console.log('[user] [scale] Data recorded: ' + JSON.stringify(this.data.record));
          break;
        default:
          wx.showToast({
            title: '请选择调料',
            icon: 'error',
            duration: 2000
          })
          return;
      }

      // 目测插入函数该猫着的地方
      this.insertData()
      wx.showToast({
        title: '数据已记录',
        icon: 'success',
        duration: 2000
      })
    } else {
      // 模拟插入数据
      this.insertData()
      wx.showToast({
        title: '请先连接设备',
        icon: 'error',
        duration: 2000
      })
    }
  },
  insertData: function() {
    // this.setData({
    //   record: { // 需要存储到本地的数据
    //     salt: 13, // 盐总摄入量（g）
    //     iodine: 9, // 碘总摄入量（mg）
    //     sugar:5, // 糖总摄入量（g）
    //     oil: 18 // 油总摄入量（g）
    //   }
    // })
    console.log(this.data.record)
    wx.cloud.callFunction({
      name: "setFoodData",
      data: {
        userId: '111111',
        date: this.data.dateNow,
        // oil: event.oil,
        // sugar: event.sugar,
        // salt: event.salt,
        // isIodizedSalt: event.isIodizedSalt,
        // Iodine: event.Iodine,
        IodineSalt: 0,
        comment: this.data.remark,
        salt: this.data.record.salt,
        Iodine: this.data.record.iodine,
        sugar: this.data.record.sugar,
        oil: this.data.record.oil,
      },
      success: res => {
        // output: res.result === 3
        console.log(res)
      },
      fail: err => {
        // handle error
      },
      complete: () => {
        // ...
      }
    })
  }
})
